<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info"
                  show-icon />

        <!-- 表格顶部菜单 -->
        <!-- 自定义按钮请使用插槽，甚至公共搜索也可以使用具名插槽渲染，参见文档 -->

<!--        <div>
            <el-radio-group v-model="status_1" size="large" @click="onComSearchOrderStatus">
                <el-radio-button label="0,1,2,3">全部</el-radio-button>
                <el-radio-button label="2">待审核 <span style="color: red;font-weight: bold">{{count2}}</span></el-radio-button>
                <el-radio-button label="1">上架中 <span style="color: red;font-weight: bold">{{count1}}</span></el-radio-button>
                <el-radio-button label="0">已下架 <span style="color: red;font-weight: bold">{{count0}}</span></el-radio-button>
                <el-radio-button label="3">未通过 <span style="color: red;font-weight: bold">{{count3}}</span></el-radio-button>
            </el-radio-group>
        </div>-->

        <TableHeader :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
                     :quick-search-placeholder="t('Quick search placeholder', { fields: t('goods.quick Search Fields') })">



            <el-popconfirm
                v-if="auth_goods_down_up"
                @confirm="goods_up"
                confirm-button-text="确认"
                cancel-button-text="取消"
                confirmButtonType="success"
                title="确认上架勾选的商品吗?"
                :disabled="baTable.table.selection!.length > 0 ? false : true"
            >
                <template #reference>
                    <div class="mlr-12" style="margin-left: 12px;">
                        <el-tooltip content="批量上架" placement="top">
                            <el-button
                                v-blur
                                :disabled="baTable.table.selection!.length > 0 ? false : true"
                                class="table-header-operate"
                                type="success"
                            >
                                <Icon color="#ffffff" name="fa fa-arrow-up" />
                                <span class="table-header-operate-text">批量上架</span>
                            </el-button>
                        </el-tooltip>
                    </div>
                </template>
            </el-popconfirm>
            <el-popconfirm
                v-if="auth_goods_down_up"
                @confirm="goods_down"
                confirm-button-text="确认"
                cancel-button-text="取消"
                confirmButtonType="success"
                title="确认下架勾选的商品吗?"
                :disabled="baTable.table.selection!.length > 0 ? false : true"
            >
                <template #reference>
                    <div class="mlr-12" style="margin-left: 12px;">
                        <el-tooltip content="批量下架" placement="top">
                            <el-button
                                v-blur
                                :disabled="baTable.table.selection!.length > 0 ? false : true"
                                class="table-header-operate"
                                type="warning"
                            >
                                <Icon color="#ffffff" name="fa fa-arrow-down" />
                                <span class="table-header-operate-text">批量下架</span>
                            </el-button>
                        </el-tooltip>
                    </div>
                </template>
            </el-popconfirm>
        </TableHeader>

        <!-- 表格 -->
        <!-- 表格列有多种自定义渲染方式，比如自定义组件、具名插槽等，参见文档 -->
        <!-- 要使用 el-table 组件原有的属性，直接加在 Table 标签上即可 -->
        <Table ref="tableRef">

        </Table>

        <!-- 表单 -->
        <PopupForm  activeName = 'goods_info' />

        <!--设置sku-->
        <el-dialog v-model="set_sku_show"
                   class="ba-operate-dialog"
                   :fullscreen = "true"
                   :close-on-click-modal="false"
                   @close="close_sku()"
                   :draggable="true" :align-center="true">

            <template #header>
                <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                    规格设置
                </div>
            </template>

            <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">

                <div

                    class="ba-operate-form"
                    :class="'ba-' + baTable.form.operate + '-form'"
                >

                    <div style="margin: 0px 80px 0px 80px">
                        <div style="">
                            <el-input v-model="specName" style="width: 50%" ref="InpuSpecRef" placeholder="请输入规格属性">
                                <!-- @keyup.enter="addSpecName()"-->
                                <template #append>
                                    <el-button type="primary" size="small" @click="addSpecName()">添加规格</el-button>
                                </template>
                            </el-input>
                            <!--                    <el-popover width="370" placement="bottom" trigger="click">-->
                            <!--                        <div>-->
                            <!--                            <el-input v-model="specName" ref="InpuSpecRef" @keyup.enter="addSpecName()" placeholder="请输入规格名称">-->
                            <!--                                <template #append>-->
                            <!--                                    <el-button type="primary" size="small" @click="addSpecName()">添加规格名</el-button>-->
                            <!--                                </template>-->
                            <!--                            </el-input>-->
                            <!--                        </div>-->
                            <!--                        <template #reference>-->
                            <!--                            <el-button>添加规格</el-button>-->
                            <!--                        </template>-->
                            <!--                    </el-popover>-->
                        </div>
                        <div>
                            <div v-show="specData.specList.length > 0">
                                <div  style="margin-top: 10px"  v-for="(item, index) in specData.specList" :key="index">
                                    <el-card  shadow="never" style="margin-bottom: 10px;border: 1px solid var(--el-card-border-color)">
                                        <div>
                                            <h4 style="display: flex;align-items: center;">
                                        <span><el-icon class="fa fa-edit" style="cursor:pointer" @click="edit_attr_show_act(index,item.label)">

                                            </el-icon>&nbsp;&nbsp;{{ item.label }}</span>
                                                <span style="color: red;cursor:pointer" class="ml10" title="删除规格" @click="openwaringshow(1,index,'')">
                                                <el-icon class="fa fa-remove"> <!--删除规格-->
                                                </el-icon>
                                            </span>

                                            </h4>
                                        </div>
                                        <div class="display mar-top-10">
                                            <div v-for="(tagNmae, tagIndex) in item.tags" :key="tagIndex" style="">
                                                <el-tag @close="openwaringshow(2,index,tagIndex)" closable
                                                        style="margin: 0 10px;" class="display align-items">
                                                    <div class="display align-items">
                                                        <el-icon @click="edit_sku_show_act(index, tagIndex,tagNmae)"
                                                                 class="mar-right-5">
                                                            <Edit />
                                                        </el-icon>{{ tagNmae }}
                                                    </div>
                                                </el-tag>
                                            </div>
                                            <div  class="ml10">
                                                <el-input v-if="inputIndex === index && inputVisible" size="small"
                                                          ref="InputRef" v-model="inputTags"
                                                          @blur="handleInputConfirm(index, item.label)" />
                                                <!--@keyup.enter="handleInputConfirm(index, item.label)"-->
                                                <el-button style="color: #2d8cf0;" v-else size="small"
                                                           @click="onClilkInput(index)" title="添加规格值">
                                                    <el-icon><Plus /></el-icon>
                                                </el-button>
                                                <!-- <el-button type="primary" size="small" @click="onClilkInput(index)">添加规格值</el-button>-->
                                            </div>
                                        </div>
                                    </el-card>


                                </div>
                            </div>
                        </div>
                        <div style="margin: 15px 0;" class="display align-items">
                            <div class="fontsize-14 ">规格SKU</div>
                            <el-button type="primary" @click="tableSKU" class="ml10">生成SKU</el-button>
                        </div>
                        <div style="margin: 5px 0;" class="display align-items flex-wrap">
                            <div class="fontsize-14  mar-top-10">批量设置SKU</div>
                            <div  v-for="(item, index) in tableHader" :key="index" class="mar-right-10 mar-top-10">
                                <el-input-number   v-if="item.type == 'number' || item.type == 'intnumber'"   style="width: 120px;"  controls-position="right"
                                                   v-model="item.val" :placeholder="item.label" :precision="item.type=='number'?2:0" value-on-clear="null" />
<!--                                <el-input  v-model="item.val" style="width: 160px;" :placeholder="item.label" v-if="item.type=='input'" />-->
                            </div>
                            <el-button @click="settings" class="ml10 mar-top-10">批量设置</el-button>
                        </div>
                        <div></div>
                        <el-table :data="submitList" border  class="mar-top-10">
                            <el-table-column v-for="(item, index) in tableHader" :label="item.label" :key="index">


                                <template #default="{ $index }">
                                    <el-text v-if="item.label === '规格'" class="mx-1"
                                             v-for="(item2, index2) in submitList[$index][item.key].split(',')">
                                        <p>{{submitList[$index][`skuName${index2 + 1}`]}} :
                                            {{submitList[$index][`skuValue${index2 + 1}`]}}</p>
                                    </el-text>
                                    <el-input-number v-else-if="item.label === '售价' || item.label === '原价' || item.label === '成本价'"
                                                     v-model="submitList[$index][item.key]" :precision="2" size="small" />
                                    <el-input-number v-else-if="item.label === '库存'" v-model="submitList[$index][item.key]"
                                                     size="small" />
                                    <el-input v-else v-model="submitList[$index][item.key]" size="small" />
                                </template>
                            </el-table-column>

                        </el-table>
                    </div>

                </div>
            </el-scrollbar>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="close_sku()">取消</el-button>
                    <el-button type="primary" @click="set_sku">
                        提交
                    </el-button>
                </div>
            </template>
        </el-dialog>


        <el-dialog v-model="edit_sku_show" title="编辑规格值" width="600" draggable align-center>
            <!--                <FormItem :label="'规格名称'" type="string" v-model="edit_sku_val" />-->

            <el-form-item >
                <el-input v-model="edit_sku_val" />
            </el-form-item>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="edit_sku_show = false">取消</el-button>
                    <el-button type="primary" @click="edit_sku_sub()">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 编辑弹框 -->
        <el-dialog v-model="edit_attr_show" title="编辑规格名" width="600"  draggable align-center>
            <!--            <FormItem :label="'规格名称'" type="string" v-model="edit_attr_val" />-->
            <el-form-item >
                <el-input v-model="edit_attr_val" />
            </el-form-item>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="edit_attr_show = false">取消</el-button>
                    <el-button type="primary" @click="edit_attr_sub()">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 删除确认框 -->
        <el-dialog
            v-model="Warningshow"
            title="警告"
            width="500"
            align-center
        >
            <div class="display align-items">
                <i class="el-icon el-message-box__status el-message-box-icon--warning"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><path fill="currentColor" d="M512 64a448 448 0 1 1 0 896 448 448 0 0 1 0-896m0 192a58.432 58.432 0 0 0-58.24 63.744l23.36 256.384a35.072 35.072 0 0 0 69.76 0l23.296-256.384A58.432 58.432 0 0 0 512 256m0 512a51.2 51.2 0 1 0 0-102.4 51.2 51.2 0 0 0 0 102.4"></path></svg></i>
                <div class="ml10" style="margin-left: 30px;margin-top: 7px">{{Warningtxt}}</div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="Warningshow = false">取消</el-button>
                    <el-button type="primary" @click="handleWarning">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, nextTick, watch, provide, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import PopupForm from './popupForm.vue'
import { baTableApi } from '/@/api/common'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import createAxios from "/@/utils/axios";
import { ElMessage } from "element-plus";
// import Close from "/@/utils/axios";

import {
    Check,
    Delete,
    Edit,
    Plus,
    Message,
    Search,
    Star,
} from '@element-plus/icons-vue'
import FormItem from "/@/components/formItem/index.vue";
import {auth, getArrayKey} from "/@/utils/common";
import {cloneDeep} from "lodash-es";

defineOptions({
    name: 'goods',
})

const { t } = useI18n()
const tableRef = ref()
const optButtons : OptButton[] = defaultOptButtons(['weigh-sort', 'edit', 'delete'])


optButtons.push(

    {
        render: 'tipButton',
        name: 'set_sku',
        title: '规格设置',
        text: '',
        type: 'warning',
        icon: 'el-icon-Grid',
        class: 'table-row-info',
        click(row, field) {
            id.value = row.id;
            set_sku_pag();

        },
        display: (row, field) => {
            if (row.is_sku == 1) {
                return true;
            }
        },
    },
)
/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/Goods/'),
    {
        pk: 'id',
        column: [
            { type: 'selection', align: 'center', operator: false },
            { label: t('goods.id'), prop: 'id', align: 'center', width: 70, operator: false, sortable: 'custom' },
            // 商家列已移除

            { label: t('goods.goodsclass__name'),width:150, prop: 'goodsclass.name', operator: false , align: 'center', operatorPlaceholder: t('Fuzzy query') },
            { label: t('goods.goodsclass__name'), prop: 'goodsclass.id',show:false, comSearchRender: 'remoteSelect', remote: {pk: 'id', remoteUrl: '/admin/goodsclass/index',}},

            { label: t('goods.reccategory_id'),width:150, prop: 'reccategory.name', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: false },
            { label: t('goods.reccategory_id'), prop: 'reccategory.id',show:false, comSearchRender: 'remoteSelect', remote: {pk: 'id', remoteUrl: '/admin/reccategory/index',}},

            { label: t('goods.name'),width:200, prop: 'name', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            // { label: t('goods.delivery_type'),width:150, prop: 'delivery_type', align: 'center', render: 'tags', operator: 'FIND_IN_SET', sortable: false, replaceValue: { '1': t('goods.delivery_type 1'), '2': t('goods.delivery_type 2') } },
            { label: t('goods.image'),width:120, prop: 'image', align: 'center', render: 'image', operator: false },
            // { label: t('goods.images'), prop: 'images', align: 'center', render: 'images', operator: false },
            { label: t('goods.status'),width:150, prop: 'status', align: 'center', render: 'tag', operator: 'eq', sortable: false, replaceValue: { '0': t('goods.status 0'), '1': t('goods.status 1'), '2': t('goods.status 2'), '3': t('goods.status 3') } },
            { label: t('goods.is_sku'),width:120, prop: 'is_sku', align: 'center', render: 'tag', operator: 'eq', sortable: false, replaceValue: { '0': t('goods.is_sku 0'), '1': t('goods.is_sku 1') } },
            { label: t('goods.is_pos'),width:120, prop: 'is_pos', align: 'center', render: 'tag', operator: 'eq', sortable: false, replaceValue: { '0': t('goods.is_pos 0'), '1': t('goods.is_pos 1'), 0: t('goods.is_pos 0'), 1: t('goods.is_pos 1'), null: t('goods.is_pos 0'), undefined: t('goods.is_pos 0') } },
            // { label: t('goods.original_price'),width:110, prop: 'original_price', align: 'center', operator: false, sortable: false },
            { label: t('goods.price'),width:110, prop: 'price', align: 'center', operator: false, sortable: false },
            { label: t('goods.postage'),width:110, prop: 'postage', align: 'center', operator: false, sortable: false },
            { label: t('goods.sales'),width:120, prop: 'sales', align: 'center', operator: false, sortable: 'custom' },
            //{ label: t('goods.coin_num'),width:110, prop: 'coin_num', align: 'center', operator: false, sortable: 'custom'},
            //{ label: t('goods.back_buy_money'),width:110, prop: 'back_buy_money', align: 'center', operator: false, sortable: 'custom'},
            //{ label: t('goods.directly_return_money'),width:110, prop: 'directly_return_money', align: 'center', operator: false, sortable: 'custom'},
            { label: t('goods.is_limit'),width:110, prop: 'is_limit', align: 'center', sortable: 'custom', render: 'tag', operator: 'eq', replaceValue: { '0': t('goods.is_limit 0'), '1': t('goods.is_limit 1') }},
            { label: t('goods.limit_num'),width:110, prop: 'limit_num', align: 'center', operator: false, sortable: 'custom'},
            // { label: t('goods.commission_than'),width:150, prop: 'commission_than', align: 'center', operator: false, sortable: 'custom'},
            // { label: t('goods.push_than'),width:150, prop: 'push_than', align: 'center', operator: false, sortable: 'custom'},
            // { label: t('goods.shop_push_than'),width:170, prop: 'shop_push_than', align: 'center', operator: false, sortable: 'custom'},
            // { label: t('goods.shop_indirect_than'),width:170, prop: 'shop_indirect_than', align: 'center', operator: false, sortable: 'custom'},
            // { label: t('goods.free_shipping'),width:150, prop: 'free_shipping', align: 'center', render: 'tag', operator: 'eq', sortable: false, replaceValue: { '0': t('goods.free_shipping 0'), '1': t('goods.free_shipping 1') } },

            { label: t('goods.weigh'),width:150, prop: 'weigh', align: 'center', operator: false, sortable: 'custom' },
            { label: t('goods.create_time'), prop: 'create_time', align: 'center', render: 'datetime', operator: 'RANGE', sortable: 'custom', width: 160, timeFormat: 'yyyy-mm-dd hh:MM:ss' },
            // { label: t('goods.update_time'), prop: 'update_time', align: 'center', render: 'datetime', operator: 'RANGE', sortable: 'custom', width: 160, timeFormat: 'yyyy-mm-dd hh:MM:ss' },
            { label: t('Operate'), align: 'center', width: 140, render: 'buttons', buttons: optButtons, operator: false,fixed:'right' },
        ],
        dblClickNotEditColumn: [undefined],
        defaultOrder: { prop: 'weigh', order: 'desc' },
    },
    {
        defaultItems: { delivery_type: [1, 2], is_sku: '0', is_pos: '0', price: '', cost_price: 0, base_sales: 0, stock: '', weigh: 0, free_shipping: 1, coin_num: 0, back_buy_money: 0, directly_return_money: 0 , commission_than: 0,push_than:0,shop_push_than:0,shop_indirect_than:0,coin_than:0,back_than:0, postage: 0 },
    }, {
        mount(){

        }
    }
    , {
        runBefore(action: string, data: any) {
            if (action === 'onSubmit') {
                // 确保这些字段在提交时是数字格式
                const numberFields = ['direct_bonus', 'see_order_bonus', 'level_bonus', 'postage'];
                if (data.items) {
                    numberFields.forEach(field => {
                        if (data.items[field] !== null && data.items[field] !== undefined && data.items[field] !== '') {
                            data.items[field] = Number(data.items[field]);
                        } else {
                            data.items[field] = 0;
                        }
                    });
                }
            }
        },
        runAfter(action: string, data: any) {
            if (action === 'requestEdit' && data.res) {
                // 确保从服务器获取的数据中这些字段是数字格式
                const numberFields = ['direct_bonus', 'see_order_bonus', 'level_bonus', 'postage'];
                if (baTable.form.items) {
                    numberFields.forEach(field => {
                        if (baTable.form.items![field] !== null && baTable.form.items![field] !== undefined && baTable.form.items![field] !== '') {
                            baTable.form.items![field] = Number(baTable.form.items![field]);
                        } else {
                            baTable.form.items![field] = 0;
                        }
                    });
                }
            }
        },
        onSubmit({ res }) {
            if (res.data.is_sku == '1') {
                id.value = res.data.id;
                setTimeout(() => {
                    set_sku_pag();
                }, 1000);
            }
        },
    }
)

provide('baTable', baTable)

// 重写 requestEdit 方法，确保数据返回时转换为数字格式
baTable.requestEdit = (id: string) => {
    if (baTable.runBefore('requestEdit', { id }) === false) return
    baTable.form.loading = true
    baTable.form.items = {}
    return baTable.api
        .edit({
            [baTable.table.pk!]: id,
        })
        .then((res) => {
            baTable.form.items = res.data.row
            // 立即转换这些字段为数字格式
            const numberFields = ['direct_bonus', 'see_order_bonus', 'level_bonus', 'postage']
            if (baTable.form.items) {
                numberFields.forEach(field => {
                    if (baTable.form.items![field] !== null && baTable.form.items![field] !== undefined && baTable.form.items![field] !== '') {
                        baTable.form.items![field] = Number(baTable.form.items![field])
                    } else {
                        baTable.form.items![field] = 0
                    }
                })
            }
            baTable.runAfter('requestEdit', { res })
        })
        .catch((err) => {
            baTable.toggleForm()
            baTable.runAfter('requestEdit', { err })
        })
        .finally(() => {
            baTable.form.loading = false
        })
}

onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
})

const id = ref(0);


// ------------变量----------------
const specName = ref(''),//规格名
    inputTags = ref(''), // 规格值
    inputVisible = ref(false),
    inputIndex = ref(0),
    submitList = ref([]);
const specData = reactive({ specList: [], skuValue: {} });

const InputRef = ref(null);
const InpuSpecRef = ref(null);
const tableHader = ref([
    { label: '规格', key: 'sku',type:'text',val:null },
    { label: 'sku编码', key: 'code',type:'input',val:null },
    // { label: '原价', key: 'original_price',type:'number',val:null },
    { label: '售价', key: 'price',type:'number',val:null },
    // { label: '成本价', key: 'cost_price',type:'number',val:null },
    { label: '库存', key: 'stock',type:'intnumber',val:null }
])
// ------------变量----------------

/**
 *  规格设置
 */
const set_sku_show = ref(false);

// 展示的方法
const set_sku_pag = () => {

    createAxios({
        url: '/admin/goods/set_sku?id=' + id.value,
        method: 'get',
        data: {

        }
    }, {
        loading: true
    }, {
        text: '请求中...'
    })
        .then((res) => {
            set_sku_show.value = true;
            submitList.value = []
            specData.specList = []
            specData.skuValue = {}
            if (res.data.submitList.length > 0){
                submitList.value = res.data.submitList
                specData.specList = res.data.specData.specList
                specData.skuValue = res.data.specData.skuValue
            }
        })
        .catch((resx) => {
        })

}
// 提交的方法
const set_sku = () => {
    createAxios({
        url: '/admin/goods/set_sku',
        method: 'post',
        data: {
            id: id.value,
            submitList: submitList.value,

        }
    }, {
        loading: true
    }, {
        text: '数据提交中...'
    })
        .then((res) => {
            if (res.code == 1) {
                ElMessage({
                    message: res.msg,
                    type: 'success',
                })

                baTable.onTableHeaderAction('refresh', {})
            } else {

                ElMessage({
                    message: res.msg,
                    type: 'error',
                })
            }

            set_sku_show.value = false;
            tableHader.value.forEach(t=>{
                t.val = null
            })
        })
        .catch((resx) => {
        })
}


// ------------生命周期----------------
watch(submitList, (newValue) => {
}, { deep: true });
// ------------生命周期----------------

// -----------function-----------------
function addSpecName() {
    if (specName.value) {
        specData.specList.push({ label: specName.value, tags: [] });
        specName.value = '';
    } else {
        ElMessage.warning('请输入规格名称')
    }
}
function handleInputConfirm(index, label) {
    if (inputTags.value) {
        //找到并吧输入值push到tags里面
        specData.specList[index].tags.push(inputTags.value);
        if (!specData.skuValue[label]) specData.skuValue[label] = [inputTags.value];
        else specData.skuValue[label].push(inputTags.value);
        // tableSKU();
    }
    inputTags.value = '';
    inputVisible.value = !inputVisible.value;
}
function onClilkInput(index) {
    inputIndex.value = index; // 获取输入框下标
    inputVisible.value = !inputVisible.value; // 显示输入框
    nextTick(() => {
        InputRef.value[0]?.input?.focus();
    });
}
function onDeletSpec(index) { //删除规格
    // delete specData.skuValue[specData.specList[index].label]; //找到相对于的名称，然后删除skuValue相对于的值
    specData.specList.splice(index, 1); // 同时删除展示的标签
    // tableSKU(); //重绘数据和页面
}
function onDeletSpecValue(index, tagIndex) {//删除规格值
    // return ;
    // specData.skuValue[specData.specList[index].label].splice(tagIndex, 1);//删除tags里面的其中一个值
    specData.specList[index].tags.splice(tagIndex, 1); // 规格值
    // tableSKU();//重绘数据和页面
}

// 重绘数据和页面
function tableSKU() {
    if (specData.specList.length > 0){
        const list = specData.specList.reduce((def, item, index) => {
            const data = [];
            def.forEach(t => {
                t.skux = t.sku
                item.tags.forEach(tag => {
                    if (t.sku) {
                        if (t.skux) {
                            t.sku = t.skux + `,${tag}`;
                        } else {
                            t.sku = tag;
                        }
                    }
                    else {
                        t.sku = tag;
                    }
                    const oldValue = submitList.value.find(o => o.sku === t.sku);
                    if (oldValue) {
                        data.push({ ...oldValue })
                    }
                    else {
                        data.push({
                            ...t,
                            [`skuName${index + 1}`]: item.label,
                            [`skuValue${index + 1}`]: tag,
                            [item.label]: tag,
                            price: 0,
                            // original_price: 0,
                            // cost_price: 0,
                            stock: 0,
                            code: item.code
                        })
                    }
                })
            });
            return data;
        }, [[]]);
        const tableList = disposeSku(list);
        // console.log('tableList: ', tableList);
        submitList.value = tableList;
    }

}
function disposeSku(list) {
    const result = [];
    for (let index = 0; index < list.length; index++) {
        const item = list[index];
        const sku = [];
        for (const key in item) {
            if (key.indexOf('skuValue') >= 0) sku.push(item[key])
        }
        item.sku = sku.join(',');
        result.push(item);
    }
    return result;
}

const edit_sku_val = ref();
const edit_sku_show = ref(false);
const edit_sku_i = ref();
const edit_sku_ti = ref();
const edit_sku_show_act = (index, tagIndex, tagNmae) => {
    edit_sku_show.value = true;
    edit_sku_val.value = tagNmae;
    edit_sku_i.value = index;
    edit_sku_ti.value = tagIndex;
}
const edit_sku_sub = () => {
    edit_sku_show.value = false;
    specData.specList[edit_sku_i.value].tags[edit_sku_ti.value] = edit_sku_val.value;
}

const edit_attr_val = ref();
const edit_attr_show = ref(false);
const edit_attr_i = ref();
const edit_attr_show_act = (index, tagNmae) => {
    edit_attr_show.value = true;
    edit_attr_val.value = tagNmae;
    edit_attr_i.value = index;
}
const edit_attr_sub = () => {
    edit_attr_show.value = false;
    specData.specList[edit_attr_i.value]['label'] = edit_attr_val.value;
}


// -----------function-----------------
//批量设置
const settings = () =>{
    if (submitList.value.length > 0){
        submitList.value.forEach(item=>{
            tableHader.value.forEach(t=>{
                if(t.type!='text'){
                    if((t.type=='number'||t.type=='intnumber')&&t.val==0?!!t.val:!t.val){
                        return
                    }else{
                        item[t.key] = t.val
                    }
                }
            })
        })
    }
}
const Warningshow = ref(false)
const Warningtxt = ref('')
const deltype = ref()
const delindex = ref()
const deltagIndex = ref()
const openwaringshow=(type,index,tagIndex)=>{
    deltype.value = type
    delindex.value = index
    deltagIndex.value = tagIndex
    if(type==1){
        Warningtxt.value = '确定删除该规格组数据吗？此操作不可恢复！'
    }else{
        Warningtxt.value = '确定删除该规格值吗？此操作不可恢复！'
    }
    Warningshow.value = true
}
const handleWarning=()=>{
    if(deltype.value==1){
        onDeletSpec(delindex.value)
    }else{
        onDeletSpecValue(delindex.value,deltagIndex.value)
    }
    Warningshow.value = false
}



const auth_goods_down_up = auth({ name: '/admin/goods', subNodeName: '/admin/goods/goods_down_up' })
const goods_down = () => {
    goods_down_up(0)
}
const goods_up = () => {
    goods_down_up(1)
}

function goods_down_up(status)
{
    var ids = baTable.getSelectionIds()

    createAxios({
        url: '/admin/goods/goods_down_up',
        method: 'post',
        data: {
            ids: ids,
            status: status,
        }
    },{
        loading:true
    },{
        text: '数据提交中...'
    })
        .then((res) => {

            ElMessage({
                message: res.msg,
                type: 'success',
            })
            baTable.onTableHeaderAction('refresh', {})

        })
        .catch((resx) => {
        })
}

const close_sku = () => {

    set_sku_show.value = false;
}




const status_1 = ref('0,1,2,3')
const count0 = ref()
const count1 = ref()
const count2 = ref()
const count3 = ref()
const onComSearchOrderStatus = () => {
    // 展开公共搜索
    // baTable.table.showComSearch = true

    /**
     * 公共搜索表单赋值
     * 范围搜索有两个输入框，输入框绑定变量分别为 `字段名-start` 和 `字段名-end`
     * 当前是范围搜索的等于示例，所以 start 和 end 均为1
     */
    // baTable.comSearch.form = Object.assign(baTable.comSearch.form, {
    //     'order_status':order_status_val,
    // })

    /**
     * 组装发送给服务端的筛选条件数据
     */
    const fieldDataTemp = baTable.comSearch.fieldData.get('status') // 获取 id 字段的公共搜索数据，它由 baTable 自动初始化
    if (fieldDataTemp) {
        // 筛选数据组装
        let comSearchData: comSearchData = {
            field: 'status', // 筛选字段
            val: status_1.value, // 范围查询的 start 值和 end 值，直接使用逗号分隔
            operator: 'IN', // 公共搜索操作符号
            render: fieldDataTemp.render, // 字段渲染方案
        }

        let index = getArrayKey(baTable.table.filter!.search!, 'field', 'status') // 查询是否已经有 id 字段的筛选数据
        if (!index) {
            // push 到要发送给服务端的筛选条件数组中
            baTable.table.filter!.search!.push(comSearchData) // 无则 push
        } else {
            baTable.table.filter!.search![index] = comSearchData // 有则重新赋值
        }

        // 重新请求表格数据（刷新表格）
        baTable.onTableHeaderAction('refresh', {})
    } else {
        console.log('没有找到 status 字段的公共搜索数据，因为该字段禁止了公共搜索')
    }
}



const activeName = ref('goods_info')
/**
 * 打开表单
 * @param operate 操作:Add=添加,Edit=编辑
 * @param operateIds 被操作项的数组:Add=[],Edit=[1,2,...]
 */
baTable.toggleForm = (operate = '', operateIds: string[] = []) => {

    if (baTable.runBefore('toggleForm', { operate, operateIds }) === false) return
    if (baTable.form.ref) {
        baTable.form.ref.resetFields()
    }
    if (operate == 'Edit') {
        if (!operateIds.length) {
            return false
        }
        baTable.requestEdit(operateIds[0])
    } else if (operate == 'Add') {
        baTable.form.items = cloneDeep(baTable.form.defaultItems)
    }
    baTable.form.operate = operate
    baTable.form.operateIds = operateIds
    baTable.form.activeName = activeName.value;
    baTable.runAfter('toggleForm', { operate, operateIds})
}

</script>

<style scoped lang="scss">

@import 'index.scss';

:deep(.ba-operate-dialog .el-dialog__body) {
    height: 91vh !important;
}

</style>
